package com.hugoo.core.util;

import java.io.*;

/**
 *
 * @author Lovelock.Chan
 */
public class FileEncode {

    BufferedReader br;
    int pos = 0;

    public FileEncode(File file) throws FileNotFoundException, IOException {
        InputStream fis = new FileInputStream(file);
        String encoding = getEncoding(fis);
        br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
        br.skip(pos);
    }

    public FileEncode(String impFilePath) throws FileNotFoundException, IOException {
        this(new File(impFilePath));
    }

    public BufferedReader getBufferedReader() throws UnsupportedEncodingException, IOException {
        return br;
    }

    public void close() {
        try {
            if (br != null) {
                br.close();
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }

    private String getEncoding(InputStream fis) throws IOException {
        String charset = null;
        try {
            byte[] bom = new byte[20480];
            int read = fis.read(bom);
            if (read == -1) {
                return null;
            }
            if (bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE) {
                charset = "UTF-16LE";
            } else if (bom[0] == (byte) 0xFE
                    && bom[1] == (byte) 0xFF) {
                charset = "UTF-16BE";
            } else if (bom[0] == (byte) 0xEF
                    && bom[1] == (byte) 0xBB
                    && bom[2] == (byte) 0xBF) {
                charset = "UTF-8";
                pos = 1;
            } else {
                for (int i = 0; i < 20480; i++) {
                    if (bom[i] > 0 && bom[i] < 128) {
                        //ASCII字符
                    } else if ((bom[i] & 0xE0) == 0xC0 && (bom[++i] & 0xC0) == 0x80) {
                        //  charset = "UTF-8";
                    } else if ((bom[i] & 0xF0) == 0xE0 && (bom[++i] & 0xC0) == 0x80 && (bom[++i] & 0xC0) == 0x80) {
                        charset = "UTF-8";
                    } else {
                        charset = "GBK";
                    }
                    if (TL.isNotEmpty(charset)) {
                        break;
                    }
                }
            }
            if (TL.isEmpty(charset)) {
                charset = "GBK";
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
        return charset;
    }
}
